const jwt = require('jsonwebtoken')
const config = require('../config')
const Cookies = require('cookies')

let isEmpty = obj => {
  if (obj === undefined || obj === 'undefined' || obj === null || obj === 'null' || obj === '') {
    return true;
  } else {
    return false;
  }
}
let decode = token => {
  token = token.substr(7)
  decoded = jwt.decode(token, {complete: true})
  return decoded
}
let getSub = token => {
  let decoded = decode(token)
  return JSON.parse(decoded.payload.sub)
}

let parseUser = async obj => {
  if (!obj) {
    return
  }
  let token = ''
  if (typeof obj === 'string') {
    token = obj
  } else if (obj.headers) {
    let cookies = new Cookies(obj, null)
    token = cookies.get('Authorization')
  }
  if (token) {
    try {
      let decoded = await jwt.verify(token, new Buffer(config.secret, 'base64'), { algorithms: ['HS512'] })
      return JSON.parse(decoded.sub)
    } catch (error) {
      console.log(error)
      return
    }
  }
}
module.exports = {
  isEmpty,
  decode,
  getSub,
  parseUser
}